"""
5. 字符编码转换
编写一个Python程序，将一个字符串从ASCII编码转换为Unicode编码，并再转换为GBK编码。最后，将GBK编码的字符串转换回Unicode编码
"""


def convert_encoding(text):
    print("原始字符串:", text)
    print("\n开始编码转换过程...")

    try:
        # 将字符串转换为ASCII编码（仅限ASCII字符）
        try:
            ascii_encoded = text.encode('ascii')
            print(f"\n1. 转换为ASCII编码:")
            print(f"二进制形式: {ascii_encoded}")
            print(f"十六进制形式: {ascii_encoded.hex()}")
        except UnicodeEncodeError:
            print("\n1. 转换为ASCII编码失败：字符串包含非ASCII字符")
            ascii_encoded = text.encode('ascii', errors='ignore')
            print(f"忽略非ASCII字符后的结果: {ascii_encoded}")

        # 转换为Unicode编码（UTF-8）
        unicode_encoded = text.encode('utf-8')
        print(f"\n2. 转换为Unicode编码(UTF-8):")
        print(f"二进制形式: {unicode_encoded}")
        print(f"十六进制形式: {unicode_encoded.hex()}")

        # 转换为GBK编码
        gbk_encoded = text.encode('gbk')
        print(f"\n3. 转换为GBK编码:")
        print(f"二进制形式: {gbk_encoded}")
        print(f"十六进制形式: {gbk_encoded.hex()}")

        # GBK解码回Unicode
        unicode_decoded = gbk_encoded.decode('gbk')
        print(f"\n4. GBK编码转回Unicode:")
        print(f"解码结果: {unicode_decoded}")

        # 验证转换是否正确
        print(f"\n验证结果:")
        print(f"原始字符串与最终字符串是否相同: {text == unicode_decoded}")

    except Exception as e:
        print(f"\n转换过程中发生错误: {str(e)}")


if __name__ == "__main__":
    # 测试包含中文和英文的字符串
    test_string = "Hello世界！123"
    convert_encoding(test_string)